<?php
/**
 * @title H 指数 II - 二分查找
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[] $citations
     * @return Integer
     */
    function hIndex($citations) {
        /**
         * @since 2021-07-12 h指数
         */
        $h = 0;

        /**
         * @since 2021-07-12 长度, 初始化
         */
        $len = count($citations);
        $s = 0;
        $e = $len-1;

        /**
         * @since 2021-07-12 二分查找
         */
        while($s<=$e){
            $mid = ($s+$e)>>1;
            $val = $citations[$mid];
            $greater = $len-$mid;

            /**
             * @since 2021-07-12 h指数, h篇至少引用h次
             */
            $h = max($h, min($val, $greater));

            /**
             * @since 2021-07-12 val已经大于等于greater, min(val, greater) = greater
             * @since 2021-07-12 如果左移, greater越来越小, h指数不可能更大
             */
            if($val >= $greater){
                $e = $mid-1;
            } else {
                /**
                 * @since 2021-07-12 同理, greater>val, min(val, greater) = val
                 * @since 2021-07-12 如果右移, val越来越小
                 */
                $s = $mid+1;
            }
        }

        /**
         * @return
         */
        return $h;
    }
}

/**
 * @url http://127.0.0.1/leetcode/202107/2021.07.12.php
 */
$datas = [
    [[0,1,3,5,6]], // 3
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->hIndex(...$data);
    // $result = $obj->($xhprof->tree($data));
    // $result = $obj->($xhprof->listNode($data));
    // $result = $obj->find(...$data);
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat(PHP_EOL, 3);
    echo str_repeat("<br>", 3);
}

// foreach ($datas as $data){
//     $obj = new $data[0][0](...$data[1][0]);
//
//     for ($i=1; $i<count($data[0]); $i++){
//         $func = $data[0][$i];
//         $param = $data[1][$i];
//         $result = $obj->$func(...$param);
//
//         echo $data[0][$i] ."(\"". implode(",", $data[1][$i]) ."\") ";
//             if($result === true){
//                 echo "True";
//             } elseif($result === false) {
//                 echo "False";
//             } elseif($result === null) {
//                 echo "Null";
//             } elseif(is_array($result)) {
//                 var_dump($result);
//             } else {
//                 echo $result;
//             }
//         echo PHP_EOL;
//     }
//
//     echo str_repeat(PHP_EOL, 3);
// }
$xhprof->end();
